package com.jsb.laundry.common.utils.push;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.jsb.laundry.common.utils.http.HttpUtil;
import com.jsb.laundry.model.factory.WxSend;
import org.apache.http.HttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClientBuilder;
import org.apache.http.util.EntityUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.cloud.context.config.annotation.RefreshScope;
import org.springframework.stereotype.Component;

import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

@Component
public class WxSendServiceImpl {

    private static final Logger LOGGER = LoggerFactory.getLogger(WxSendServiceImpl.class);


    private static String wxUserAppId;

    private static String wxUserAppSecret;

    private static String wxRiderAppId;

    private static String wxRiderAppSecret;

    @Value("${wx.appId}")
    public void setWxUserAppId(String wxUserAppId) {
        this.wxUserAppId = wxUserAppId;
    }

    @Value("${wx.appSecret}")
    public void setWxUserAppSecret(String wxUserAppSecret) {
        this.wxUserAppSecret = wxUserAppSecret;
    }

    @Value("${wxRider.appId}")
    public void setWxRiderAppId(String wxRiderAppId) {
        this.wxRiderAppId = wxRiderAppId;
    }

    @Value("${wxRider.appSecret}")
    public void setWxRiderAppSecret(String wxRiderAppSecret) {
        this.wxRiderAppSecret = wxRiderAppSecret;
    }

    /**
     * 推送用户 订阅号推送
     */
    public static void send(WxSend.WxUserSend wxSend) {

        LOGGER.info("订阅号推送：{}", wxSend);

        /**
         * 创建一个post请求
         * 获取手机号
         */
        String appId = null;
        String appSecret = null;
        //骑手
        if (wxSend.getStatus() == 0) {
            appId = wxRiderAppId;
            appSecret = wxRiderAppSecret;
        }
        //用户
        if (wxSend.getStatus() == 1) {
            appId = wxUserAppId;
            appSecret = wxUserAppSecret;
        }
        String accessToken = accessToken(appId, appSecret);
        CloseableHttpClient client11 = HttpClientBuilder.create().build();
        HttpPost post = new HttpPost("https://api.weixin.qq.com/cgi-bin/message/subscribe/send?access_token=" + accessToken);


        Map data = new HashMap();
        HashMap<String, String> o1 = new HashMap<>();
        o1.put("value", wxSend.getCharacter_string1());
        HashMap<String, String> o2 = new HashMap<>();
        o2.put("value", wxSend.getCharacter_string4());
        HashMap<String, String> o3 = new HashMap<>();
        o3.put("value", wxSend.getThing2());
        HashMap<String, String> o4 = new HashMap<>();
        o4.put("value", wxSend.getThing3());
        HashMap<String, String> o5 = new HashMap<>();
        o5.put("value", wxSend.getTime5());
        data.put("character_string1", o1);
        data.put("character_string4", o2);
        data.put("thing2", o3);
        data.put("thing3", o4);
        data.put("time5", o5);

        JSONObject jsonb = new JSONObject();
        jsonb.put("data", data);
        jsonb.put("touser", wxSend.getOpenId());
        jsonb.put("miniprogram_state", wxSend.getMiniprogram_state());
        jsonb.put("lang", wxSend.getLang());
        jsonb.put("template_id", wxSend.getTemplateId());
        StringEntity postingString = new StringEntity(jsonb.toString(), "UTF-8");
        post.setEntity(postingString);
        post.setHeader("Content-type", "application/json");
        HttpResponse response = null;
        try {
            response = client11.execute(post);
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
        String content = null;
        try {
            content = EntityUtils.toString(response.getEntity());
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
        JSONObject ss = JSON.parseObject(content);
        LOGGER.info("订阅号推送返回值：{}", ss);
    }

    public static String accessToken(String appId, String appSecret) {
        String s = HttpUtil.sendGet("https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appId=" + appId + "&secret=" + appSecret, null, null, null);
        JSONObject jsonObject = JSONObject.parseObject(s);
        String accessToken = jsonObject.getString("access_token");
        return accessToken;
    }

    /**
     * 推送给骑手 公众号推送
     *
     * @param data
     * @param openId
     */
    public static void sendLaundry(JSONObject data, String openId) {
        JSONObject object = new JSONObject();

        JSONObject jsonObject1 = new JSONObject();
        jsonObject1.put("appid", wxRiderAppId);

        object.put("touser", openId);
        object.put("template_id", "UeSbOHkNikaNkof_egGr-Nm2rAJ7ag_18rT1TOEVm4A");
        object.put("miniprogram", jsonObject1);
        object.put("data", data);

        String token = accessToken("wxa808024765c753cb", "7333cc2d01b75703f350f4a1aa6cdf4d");


        CloseableHttpClient client11 = HttpClientBuilder.create().build();
        HttpPost post = new HttpPost("https://api.weixin.qq.com/cgi-bin/message/template/send?access_token=" + token);
        StringEntity postingString = new StringEntity(object.toString(), "UTF-8");
        post.setEntity(postingString);
        post.setHeader("Content-type", "application/json");
        HttpResponse response = null;
        try {
            response = client11.execute(post);
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
        String content = null;
        try {
            content = EntityUtils.toString(response.getEntity());
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
        JSONObject ss = JSON.parseObject(content);
        LOGGER.info("推送骑手:{}", ss);
    }


//    public static void sendLaundry(JSONObject data, String openId) {
//        LOGGER.info("推送给骑手 公众号推送：{}", data, openId);
//        JSONObject object = new JSONObject();
//
//        JSONObject jsonObject1 = new JSONObject();
//        jsonObject1.put("appid", "wx66259c2db83de8c2");
//
//        object.put("touser", openId);
//        object.put("template_id", "UeSbOHkNikaNkof_egGr-Nm2rAJ7ag_18rT1TOEVm4A");
//        object.put("miniprogram", jsonObject1);
//        object.put("data", data);
//
//        String token = accessToken("wxa808024765c753cb", "7333cc2d01b75703f350f4a1aa6cdf4d");
//
//        CloseableHttpClient client11 = HttpClientBuilder.create().build();
//        HttpPost post = new HttpPost("https://api.weixin.qq.com/cgi-bin/message/template/send?access_token=" + token);
//        StringEntity postingString = new StringEntity(object.toString(), "UTF-8");
//        post.setEntity(postingString);
//        post.setHeader("Content-type", "application/json");
//        HttpResponse response = null;
//        try {
//            response = client11.execute(post);
//        } catch (IOException e) {
//            throw new RuntimeException(e);
//        }
//        String content = null;
//        try {
//            content = EntityUtils.toString(response.getEntity());
//        } catch (IOException e) {
//            throw new RuntimeException(e);
//        }
//        JSONObject ss = JSON.parseObject(content);
//        LOGGER.info("推送给骑手 公众号推送返回值：{}", ss);
//    }

}
